package com.ea.service.impl;

import com.ea.common.constant.RedisKeyConstants;
import com.ea.common.enums.OperationResultCode;
import com.ea.common.exception.ServiceException;
import com.ea.common.util.RedisUtil;
import com.ea.service.UploadImgService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @author NAME-L
 * @Description TODO
 * @className uploadImgServiceImpl
 * @date 2023-03-01 21:50:33
 */
@Service
public class uploadImgServiceImpl implements UploadImgService {

    private static final Logger logger = LoggerFactory.getLogger(uploadImgServiceImpl.class);

    @Autowired
    private RedisUtil redisUtil;

    @Value("${file.upload.path}")
    private String path;

    @Override
    public String uploadImgFile(MultipartFile picture) {
        logger.info("进入图片上传，图片文件：{}", picture.getName());
        File filePath = new File(path);
        logger.info("图片保存路径:{}", path);
        logger.info("filePath.exists():{}",filePath.exists());
        logger.info("filePath.isDirectory():{}",filePath.isDirectory());
        if (!filePath.exists() ) {
            logger.info("图片存储路径不存在，创建目录：{}", filePath);
            filePath.mkdirs();
        }
        // 获取原始文件名称（包含格式）
        String originalFileName = picture.getOriginalFilename();
        if (StringUtils.isEmpty(originalFileName)) {
            logger.error("图片名称为空！");
            throw new ServiceException(OperationResultCode.SYSTEM_ERROR);
        }
        //获取文件类型，以最后一个.为标识
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        logger.info("文件类型:{}", type);
        //获取文件名称（不包含格式）
        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));
        logger.info("文件名称:{}", name);
        boolean exists = redisUtil.hasKey(RedisKeyConstants.FLOWER_UPLOAD_IMG_NAME + originalFileName);
        if (exists) {
            return originalFileName;
        } else {
            //在指定路径下创建一个文件夹
            File targetFile = new File(path, originalFileName);
            logger.info("图片上传地址:{}", path + "/" + originalFileName);
            //将文件保存到服务器指定地址
            try {
                picture.transferTo(targetFile);
                redisUtil.set(RedisKeyConstants.FLOWER_UPLOAD_IMG_NAME + originalFileName, originalFileName , 60 * 60 * 3);
                return originalFileName;
            } catch (Exception e) {
                logger.info("上传失败");
                e.printStackTrace();
                return null;
            }

        }
    }
}
